package com.example.demo.base.aop;

import com.example.demo.base.bean.BaseResp;
import com.example.demo.base.bean.Meta;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by zhu yingzhi on 2017/8/31.
 *
 * @author yingzhi zhu
 * aop 配置类 拦截所有controller 请求 并返回指定格式的返回信息。
 */
@Aspect
@Component
public class ControllerAspect {
    private final static Logger logger = LoggerFactory.getLogger(ControllerAspect.class);//参数为当前使用的类名
    /**
     * 对返回值不做任何处理的Url
     */
    private final static String[] UN_INTERCEPT_URL = new String[]{
            "/test/dsad"
    };

    @Pointcut("execution(public * com.example.demo.business.controller..*.*(..))")
    public void cutAspect() {
    }

//    @Before("cutAspect()")
//    public void doBefore(JoinPoint joinPoint){
//        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        HttpServletRequest request =  attributes.getRequest();
//        //url
//        logger.info("url ={}",request.getRequestURI());
//        //method
//        logger.info("method={}",request.getMethod());
//        //ip
//        logger.info("ip={}",request.getRemoteAddr());
//        //类方法
//        logger.info("class_method={}",joinPoint.getSignature().getDeclaringTypeName()+'.'+ joinPoint.getSignature().getName());//获取类名及类方法
//        //参数
//        logger.info("args={}",joinPoint.getArgs());
//    }

    @Around("cutAspect()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        //日志打印
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String requestUrl = request.getRequestURI();
        request.getParameterMap().forEach((key, value) -> {
            logger.info("key ={} value={}", key, value);
        });
        logger.info("url ={}", request.getRequestURI());

        //请求结果拦截 封装
        Object o = pjp.proceed();
        for (String urls : UN_INTERCEPT_URL) {
            if (requestUrl.contains(urls)) {
                return o;
            }
        }
        BaseResp baseBean = new BaseResp(Meta.SUCCESS,o);
        return baseBean;
    }


}
